package com.example.thegreatwall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.thegreatwall.mapper.InventoryMapper;
import com.example.thegreatwall.entity.Inventory;
import com.example.thegreatwall.service.InventoryService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService{

    /**
     * 锁库存
     * @param productId
     * @param productType
     * @param recordDate
     * @param quantity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int reqUpdinventory(int productId, int productType, String recordDate, int quantity) {
        // 1. 先查询当前库存记录（包含版本号）
        Inventory inventory = getOne(new QueryWrapper<Inventory>()
                .eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate));

        // 检查库存是否存在或充足
        if (inventory == null) {
            throw new RuntimeException("库存记录不存在");
        }
        if (inventory.getAvailableTickets() < quantity) {
            throw new RuntimeException("库存不足");
        }
        // 2. 使用乐观锁进行更新
        UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate)
                .eq("version", inventory.getVersion()) // 关键：匹配当前版本号
                .set("available_tickets", inventory.getAvailableTickets() - quantity)
                .set("locked_tickets", inventory.getLockedTickets() + quantity)
                .set("version", inventory.getVersion() + 1); // 版本号自增

        // 3. 执行更新，返回影响行数
        int affectedRows = baseMapper.update(null, updateWrapper);

        // 4. 如果影响行数为0，说明版本号已变化，更新失败
        if (affectedRows <= 0) {
            throw new RuntimeException("并发修改，更新失败"); // 抛异常触发回滚
        }
        return affectedRows > 0 ? 1 : 0;
    }

    /**
     * 真实的删除
     * @param productId
     * @param productType
     * @param recordDate
     * @param quantity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmDeduction(int productId, int productType, String recordDate, int quantity) {
        // 查询当前库存
        Inventory inventory = getOne(new QueryWrapper<Inventory>()
                .eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate));

        if (inventory == null || inventory.getLockedTickets() < quantity) {
            throw new RuntimeException("锁定库存不足或记录不存在");
        }

        // 乐观锁更新
        UpdateWrapper<Inventory> wrapper = new UpdateWrapper<>();
        wrapper.eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate)
                .eq("version", inventory.getVersion())
                .set("locked_tickets", inventory.getLockedTickets() - quantity)
                .set("version", inventory.getVersion() + 1);

        int update = baseMapper.update(null, wrapper);
        if (update <= 0) {
            throw new RuntimeException("并发修改，更新失败");
        }

        return true; // 正常执行时返回true
    }
    /**
     * 释放锁定的库存（取消订单时使用）
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean releaseLockedInventory(int productId, int productType, String recordDate, int quantity) {
        // 查询当前库存
        Inventory inventory = getOne(new QueryWrapper<Inventory>()
                .eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate));

        if (inventory == null || inventory.getLockedTickets() < quantity) {
            throw new RuntimeException("锁定库存不足或记录不存在");
        }

        // 乐观锁更新：锁定库存减少，可用库存增加
        UpdateWrapper<Inventory> wrapper = new UpdateWrapper<>();
        wrapper.eq("product_id", productId)
                .eq("product_type", productType)
                .like("record_date", recordDate)
                .eq("version", inventory.getVersion())
                .set("locked_tickets", inventory.getLockedTickets() - quantity)
                .set("available_tickets", inventory.getAvailableTickets() + quantity)
                .set("version", inventory.getVersion() + 1);

        int update = baseMapper.update(null,wrapper);
        if (update <= 0) {
            throw new RuntimeException("并发修改，更新失败");
        }
        return true;
    }

}
